﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;

namespace FuturamaKassa {
    class COMListener {

        private SerialPort port;
        private COMHandler handler;
        private Thread readThread;

        private bool run = true;
        private List<byte> byteList;

        public COMListener(COMHandler handler, SerialPort port) {

            this.port = port;
            this.handler = handler;

            readThread = new Thread(read);

            readThread.Start();
        }

        /**
         * Reads the input from the Serial Port
         */
        public void read() {

            byteList = new List<byte>();

            while (run) {

                Thread.Sleep(250);

                try {
                    int bytesToRead = port.BytesToRead;

                    if (bytesToRead > 0) {

                        while (bytesToRead > 0) {

                            for (int i = 0; i < port.BytesToRead; i++) {
                                byteList.Add((byte)port.ReadByte());
                            }

                            bytesToRead = port.BytesToRead;
                        }

                        //The total amount of bytes had to be larger then 5, else continue with the while and get more bytes
                        if ( byteList.Count > 5 ) {

                            //Checks if the bytes are right according to the protocol: <ACK><STX><DATA><EXT><CHECKSUM>
                            if (byteList[0] == 0x06 && byteList[1] == 0x02 && byteList[byteList.Count - 2] == 0x03) {

                                Console.WriteLine("Checks succeeded");

                                //Checks if the checksum is correct 
                                if (byteList[byteList.Count - 1] == RFIDFunctions.calcChecksum(byteList.ToArray())) {

                                    Console.WriteLine("Checksum Complete");

                                    //Get the 4 bytes that represents the command
                                    byte[] command = { byteList[2], byteList[3], byteList[4], byteList[5] };

                                    //Send command to the handler
                                    handler.execute(Encoding.ASCII.GetString(command), byteList);
                                }
                            }

                            //Clear list
                            byteList.Clear();
                        }
                    }

                }
                catch (TimeoutException) { }
            }
        }

        /**
         * Getters and Setters 
         */

        public bool Run {
            get { return run; }
            set { this.run = value; }
        }
    }
}
